package com.wondersgroup.core.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.codec.binary.Hex;

/**
 * 调用移通短信接口发送短信的工具
 * @author wanglei
 */
public class SMSSendUtil {
    private final SpringRestUtil util = new SpringRestUtil();
    
    private final String spsc = "00";                             // sp服务代码，可选参数，默认为 00
    private final String sa = "10690007100109";                   // 源号码，可选参数
    private final int dc = 15;                                    // 编码格式，必填参数
    private final String ecodeform = "GBK";
    
    private static String mtUrl = "http://esms.10690007.net/sms/mt";
    private static String spid = "100224";
    private static String sppassword = "wdqc224";
    private static boolean isTest = false;
    
    static {
        try {
            String send = ConfigPropertiesUtil.getValue("sms.send.msg");
            isTest = !(send!=null && "true".equalsIgnoreCase(send));
            
            String rootPath = ConfigPropertiesUtil.getValue("sms.root.path");
            if(rootPath!=null){
                mtUrl = rootPath;
            }
            String user = ConfigPropertiesUtil.getValue("sms.auth.user");
            if(user!=null){
                spid = user;
            }
            String password = ConfigPropertiesUtil.getValue("sms.auth.password");
            if(password!=null){
                sppassword = password;
            }
        } catch (Exception e) {
            Logger.getLogger(SMSSendUtil.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    
    /**
     * 将短信下行请求响应字符串解析到一个HashMap中
     * @param resStr
     * @return
     */
    public static HashMap<String,String> parseResStr(String resStr) {
        HashMap<String,String> pp = new HashMap<>();
        if(resStr!=null && !resStr.isEmpty()){
            try {
                String[] ps = resStr.split("&");
                for (String p : ps) {
                    int ix = p.indexOf("=");
                    if (ix!=-1) {
                        pp.put(p.substring(0, ix), p.substring(ix+1)); 
                    }
                }
            } catch (Exception ex) {
                Logger.getLogger(SMSSendUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return pp;
    }
    
    /**
     * 发送消息
     * @param url
     * @return 
     */
    public HashMap<String,String> send(String url){
        if(!isTest){
            try {
                String s = util.processNameValuePost(url, null, null, null).toString();
                System.out.println(s);
                return parseResStr(s);
            } catch (Exception ex) {
                Logger.getLogger(SMSSendUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }
    
    /**
     * 单条下行发送
     * @param to
     * @param content
     * @return 
     */
    public SendResponse sendMSGReq(String to, String content){
        if(to==null || to.isEmpty() || content==null || content.isEmpty()){
            return null;
        }
        try {
            // 下行号码、内容列表
            //操作命令、SP编号、SP密码，必填参数
            String command = "MT_REQUEST";
            //目标号码，必填参数
            String da = to;
            String sm = new String(Hex.encodeHex(content.getBytes(ecodeform)));
            
            if(da.length()==11){
                da = "86"+da;
            }
            
            //组成url字符串
            StringBuilder smsUrl = new StringBuilder();
            smsUrl.append(mtUrl);
            smsUrl.append("?command=").append(command);
            smsUrl.append("&spid=").append(spid);
            smsUrl.append("&sppassword=").append(sppassword);
            smsUrl.append("&spsc=").append(spsc);
            smsUrl.append("&sa=").append(sa);
            smsUrl.append("&da=").append(da);
            smsUrl.append("&sm=").append(sm);
            smsUrl.append("&dc=").append(dc);
            //smsUrl.append("&priority=").append(10);  //优先级为[1-10]，数字越大越优先
            
            System.out.println("smsUrl===" + smsUrl.toString());
            Map<String, String> resp = send(smsUrl.toString());
            SendResponse sendResponse = SendResponse.createResponse(resp);
            if(sendResponse!=null){
                List<String> mobiles = new ArrayList<>();
                mobiles.add(to);
                sendResponse.setMobiles(mobiles);
            }
            return sendResponse;
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(SMSSendUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    /**
     * 相同内容群发
     * @param toList
     * @param content
     * @return
     */
    public SendResponse sendMultiMSGReq(List<String> toList, String content){
        try {
            if(toList==null || toList.isEmpty() || content==null || content.isEmpty()){
                return null;
            }
            //如果只发送一个人
            if(toList.size()==1){
                String to = toList.get(0);
                return sendMSGReq(to, content);
            }
            
            StringBuilder toBuilder = new StringBuilder();
            List<String> mobiles = new ArrayList<>();
            for(String to : toList){
                if(to!=null && !to.trim().isEmpty()){
                    String mobile = to;
                    if(mobile.length()==11){
                        mobile = "86"+mobile;
                    }
                    if(toBuilder.length()>0){
                        toBuilder.append(",");
                    }
                    toBuilder.append(mobile);
                    mobiles.add(to);
                }
            }
            if(toBuilder.length()<=0){
                return null;
            }
            
            // 下行号码、内容列表
            //操作命令、SP编号、SP密码，必填参数
            String command = "MULTI_MT_REQUEST";
            //目标号码，必填参数
            String das = toBuilder.toString();
            String sm = new String(Hex.encodeHex(content.getBytes(ecodeform)));
            
            //组成url字符串
            StringBuilder smsUrl = new StringBuilder();
            smsUrl.append(mtUrl);
            smsUrl.append("?command=").append(command);
            smsUrl.append("&spid=").append(spid);
            smsUrl.append("&sppassword=").append(sppassword);
            smsUrl.append("&spsc=").append(spsc);
            smsUrl.append("&sa=").append(sa);
            smsUrl.append("&das=").append(das);
            smsUrl.append("&sm=").append(sm);
            smsUrl.append("&dc=").append(dc);
            //smsUrl.append("&priority=").append(10);  //优先级为[1-10]，数字越大越优先
            
            System.out.println("smsUrl===" + smsUrl.toString());
            Map<String, String> resp = send(smsUrl.toString());
            SendResponse sendResponse = SendResponse.createMultiResponse(resp);
            sendResponse.setMobiles(mobiles);
            return sendResponse;
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(SMSSendUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    /**
     * 不同内容群发
     * @param messages
     * @return
     */
    public SendResponse sendMultiXMSGReq(List<Message> messages){
        try {
            if(messages==null || messages.isEmpty()){
                return null;
            }
            //如果只发送一个人
            if(messages.size()==1 && messages.get(0)!=null){
                Message m = messages.get(0);
                return sendMSGReq(m.getSendTo(), m.getContent());
            }
            
            StringBuilder dasmBuilder = new StringBuilder();
            List<String> mobiles = new ArrayList<>();
            for(Message message : messages){
                if(message==null){
                    continue;
                }
                String to = message.getContent();
                String content = message.getContent();
                if(to==null || to.isEmpty() || content==null || content.isEmpty()){
                    continue;
                }
                
                String mobile = to;
                if(mobile.length()==11){
                    mobile = "86"+mobile;
                }
                if(dasmBuilder.length()>0){
                    dasmBuilder.append(",");
                }
                dasmBuilder.append(mobile);
                dasmBuilder.append("/");
                dasmBuilder.append(new String(Hex.encodeHex(content.getBytes(ecodeform))));
                mobiles.add(to);
            }
            
            if(dasmBuilder.length()<=0){
                return null;
            }
            
            // 下行号码、内容列表
            //操作命令、SP编号、SP密码，必填参数
            String command = "MULTIX_MT_REQUEST";
            
            //组成url字符串
            StringBuilder smsUrl = new StringBuilder();
            smsUrl.append(mtUrl);
            smsUrl.append("?command=").append(command);
            smsUrl.append("&spid=").append(spid);
            smsUrl.append("&sppassword=").append(sppassword);
            smsUrl.append("&spsc=").append(spsc);
            smsUrl.append("&sa=").append(sa);
            smsUrl.append("&dasm=").append(dasmBuilder.toString());
            smsUrl.append("&dc=").append(dc);
            //smsUrl.append("&priority=").append(10);  //优先级为[1-10]，数字越大越优先
            
            System.out.println("smsUrl===" + smsUrl.toString());
            Map<String, String> resp = send(smsUrl.toString());
            SendResponse sendResponse = SendResponse.createMultiResponse(resp);
            sendResponse.setMobiles(mobiles);
            return sendResponse;
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(SMSSendUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }    
    
    /**
     * 单条消息
     */
    public static class Message{
        private String sendTo;
        private String content;

        public Message(String sendTo, String content) {
            this.sendTo = sendTo;
            this.content = content;
        }

        public String getSendTo() {
            return sendTo;
        }

        public void setSendTo(String sendTo) {
            this.sendTo = sendTo;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
    
    /**
     * 从运营商返回的发送结果
     */
    public static class SendResponse{
        private String command;
        private String spid;
        private List<String> mtmsgids = new ArrayList<>();
        private String mtstat;
        private String mterrcode;
        private List<String> mobiles;
        /**
         * 单号码发送结果获取
         * @param map
         * @return 
         */
        public static SendResponse createResponse(Map<String,String> map){
            SendResponse response = null;
            if(map!=null && !map.isEmpty()){
                String command = map.get("command");
                String spid = map.get("spid");
                String mtmsgid = map.get("mtmsgid");
                String mtstat = map.get("mtstat");
                String mterrcode = map.get("mterrcode");
                
                response = new SendResponse();
                response.setCommand((command!=null && command.equalsIgnoreCase("null"))?null:command);
                response.setSpid((spid!=null && spid.equalsIgnoreCase("null"))?null:spid);
                response.getMtmsgids().add((mtmsgid!=null && mtmsgid.equalsIgnoreCase("null"))?null:mtmsgid);
                response.setMtstat((mtstat!=null && mtstat.equalsIgnoreCase("null"))?null:mtstat);
                response.setMterrcode((mterrcode!=null && mterrcode.equalsIgnoreCase("null"))?null:mterrcode);
            }
            return response;
        }
        
        /**
         * 多号码批量发送结果获取
         * @param map
         * @return 
         */
        public static SendResponse createMultiResponse(Map<String,String> map){
            SendResponse response = null;
            if(map!=null && !map.isEmpty()){
                String command = map.get("command");
                String spid = map.get("spid");
                String mtmsgids = map.get("mtmsgids");
                String mtstat = map.get("mtstat");
                String mterrcode = map.get("mterrcode");
                
                response = new SendResponse();
                response.setCommand((command!=null && command.equalsIgnoreCase("null"))?null:command);
                response.setSpid((spid!=null && spid.equalsIgnoreCase("null"))?null:spid);
                response.setMtstat((mtstat!=null && mtstat.equalsIgnoreCase("null"))?null:mtstat);
                response.setMterrcode((mterrcode!=null && mterrcode.equalsIgnoreCase("null"))?null:mterrcode);         
                if(mtmsgids!=null && !mtmsgids.equalsIgnoreCase("null")){
                    String[] ids = mtmsgids.split(",");
                    for(String id : ids){
                        if(id!=null && !id.trim().isEmpty()){
                            String mtmsgid = id.trim();
                            response.getMtmsgids().add((mtmsgid!=null && mtmsgid.equalsIgnoreCase("null"))?null:mtmsgid);
                        }
                    }
                }
            }
            return response;
        }
        
        public String getCommand() {
            return command;
        }

        public void setCommand(String command) {
            this.command = command;
        }

        public String getSpid() {
            return spid;
        }

        public void setSpid(String spid) {
            this.spid = spid;
        }

        public List<String> getMtmsgids() {
            return mtmsgids;
        }

        public void setMtmsgids(List<String> mtmsgids) {
            this.mtmsgids = mtmsgids;
        }

        public String getMtstat() {
            return mtstat;
        }

        public void setMtstat(String mtstat) {
            this.mtstat = mtstat;
        }

        public String getMterrcode() {
            return mterrcode;
        }

        public void setMterrcode(String mterrcode) {
            this.mterrcode = mterrcode;
        }

        public List<String> getMobiles() {
            return mobiles;
        }

        public void setMobiles(List<String> mobiles) {
            this.mobiles = mobiles;
        }
        
        public boolean isSuccess(){
            if(mtstat!=null && mterrcode!=null){
                if(mtstat.equalsIgnoreCase("ACCEPTD")){
                    return true;
                }else if(mtstat.equalsIgnoreCase("DELIVRD")){
                    return true;
                }
            }
            return false;
        }
    }
}
